package com.gohome.gohomechat.ui.activity;

import android.app.AlertDialog;
import android.content.BroadcastReceiver;
import android.content.ContentResolver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.AnimationDrawable;
import android.graphics.drawable.ColorDrawable;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.support.v4.content.LocalBroadcastManager;
import android.support.v4.view.ViewPager;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.text.Editable;
import android.text.SpannableString;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.Gravity;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.GridView;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.PopupMenu;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.easemob.chat.EMChatManager;
import com.easemob.chat.EMConversation;
import com.easemob.chat.EMMessage;
import com.easemob.chat.NormalFileMessageBody;
import com.easemob.util.PathUtil;
import com.gohome.gohomechat.GoHomeHelper;
import com.gohome.gohomechat.R;
import com.gohome.gohomechat.model.ChatEmoji;
import com.gohome.gohomechat.model.entify.Contant;
import com.gohome.gohomechat.GoHomeHelper;
import com.gohome.gohomechat.R;
import com.gohome.gohomechat.model.ChatEmoji;
import com.gohome.gohomechat.model.entify.ChatType;
import com.gohome.gohomechat.model.entify.Recorder;
import com.gohome.gohomechat.ui.adapter.ChatListViewAdapter;
import com.gohome.gohomechat.ui.adapter.ChatRecyclerViewAdapter;
import com.gohome.gohomechat.ui.adapter.FaceAdapter;
import com.gohome.gohomechat.ui.adapter.ViewPagerAdapter;
import com.gohome.gohomechat.ui.viewlistener.EaseCustomChatRowProvider;
import com.gohome.gohomechat.utils.CommonUtils;
import com.gohome.gohomechat.ui.viewlistener.EaseChatPrimaryMenuListener;
import com.gohome.gohomechat.utils.FaceConversionUtil;
import com.gohome.gohomechat.utils.MediaManager;
import com.gohome.gohomechat.utils.TextUtil;
import com.gohome.gohomechat.utils.ToastUtil;
import com.gohome.gohomechat.view.AudioRecordButton;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * Created by dllo on 16/3/4.
 */
public class ChatActivity extends BaseActivity implements View.OnClickListener, AdapterView.OnItemClickListener, ChatRecyclerViewAdapter.OnClickListener, ChatListViewAdapter.onMessageClickListener, View.OnLongClickListener {
    private static final int REQUEST_CODE_PICK_IMAGE = 1;
    protected static final String TAG2 = "img_path";

    private static final int REQUEST_CODE_SELECT_FILE = 12;
    private EaseChatPrimaryMenuListener listener;
    private final int SYSTEM_CAMERA_REQUESTCODE = 3;
    public static final int CHATTYPE_GROUP = 2;
    private Uri imageFileUri = null;
    private final int TYPE_FILE_IMAGE = 1;
    private final int TYPE_FILE_VEDIO = 2;
    private FrameLayout frameLayout;
    private LinearLayout linearLayout;
    private AudioRecordButton voiceButton; // 语音按钮；
    private View viewanim;
    private Toolbar chat_toolbar;
    private ImageView keyboard;
    private TextView chat_title_userName;
    private ListView chat_message;
    private ImageView chat_voice, chat_keyboard, chat_type, chat_face, chat_title_remove;
    private EditText chat_input;
    private Button chat_send;
    private ImageButton chat_imgbtn_back;
    private String contentName;
    private EMMessage.ChatType chattype;
    private List<EMMessage> datas;
    private ChatListViewAdapter adapter;
    private RelativeLayout chat_facechoose;
    private RecyclerView chat_recyclerView;
    private ChatRecyclerViewAdapter recyclerViewAdapter;
    private PopupWindow popupWindow;
    private int chatType;
    private EMConversation conversation;
    // 给谁发送消息
    private String toChatUsername;
    String toUserNick="";
    String myUserNick = "";
    private ChatListViewAdapter chatListViewAdapter;
    private List<Recorder> mDatas = new ArrayList<Recorder>();

    private Handler handler = new Handler(new Handler.Callback() {
        @Override
        public boolean handleMessage(Message msg) {
            datas = GoHomeHelper.getInstance().obtainChatRecord(contentName);
            adapter.addData(datas);
            chat_message.setSelection(datas.size() - 1);
            return false;
        }
    });

    public static final String NEWMessage = "新消息";

    @Override
    protected int getLayout() {
        return R.layout.activity_chat;
    }

    @Override
    protected void initPresenter() {

    }

    @Override
    protected void initView() {
        ChatType chatType= getIntent().getExtras().getParcelable("content");
        this.contentName =chatType.getChatname();
        this.chattype=chatType.getChatType();


        frameLayout = (FrameLayout) findViewById(R.id.frameLayout);
        linearLayout = (LinearLayout) findViewById(R.id.linearLayout);

        // 语音
        voiceButton = (AudioRecordButton) findViewById(R.id.recordButton);

        keyboard = (ImageView) findViewById(R.id.keyboard);
        chat_recyclerView = findView(R.id.chat_recyclerView);
        chat_facechoose = findView(R.id.chat_facechoose);
        emojis = FaceConversionUtil.getInstace().emojiLists;
        initEmojis();
        chat_imgbtn_back = findView(R.id.chat_imgbtn_back);
        chat_title_userName = findView(R.id.chat_title_userName);
        chat_toolbar = findView(R.id.chat_toolbar);
        chat_message = findView(R.id.chat_message);
        chat_voice = findView(R.id.chat_voice);
        chat_keyboard = findView(R.id.chat_keyboard);
        chat_type = findView(R.id.chat_type);
        chat_title_remove = findView(R.id.chat_title_remove);
        chat_input = findView(R.id.chat_input);
        chat_send = findView(R.id.chat_send);
        chat_face = findView(R.id.chat_face);
        adapter = new ChatListViewAdapter(this);
        recyclerViewAdapter = new ChatRecyclerViewAdapter(this);
        LocalBroadcastManager localBroadcastManager = LocalBroadcastManager.getInstance(this);
        IntentFilter intentFilter = new IntentFilter(NEWMessage);
        localBroadcastManager.registerReceiver(broadcastReceiver, intentFilter);

    }

    @Override
    protected void initData() {
        setSupportActionBar(chat_toolbar);
        chat_message.setAdapter(adapter);
        chat_recyclerView.setLayoutManager(new GridLayoutManager(this, 4));
        chat_recyclerView.setAdapter(recyclerViewAdapter);
        chat_title_userName.setText(contentName);
        handler.sendEmptyMessage(200);
        //   chat_message.setSelection(datas.size()-1);

        chat_input.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                if (count > 0) {
                    chat_type.setVisibility(View.GONE);
                    chat_send.setVisibility(View.VISIBLE);
                }
            }

            @Override
            public void afterTextChanged(Editable s) {
                if (chat_input.getText().length() == 0) {
                    chat_type.setVisibility(View.VISIBLE);
                    chat_send.setVisibility(View.GONE);
                }
            }
        });


        chat_send.setOnClickListener(this);
        chat_type.setOnClickListener(this);
        chat_input.setOnClickListener(this);
        chat_voice.setOnClickListener(this);
        chat_face.setOnClickListener(this);
        keyboard.setOnClickListener(this);
        chat_imgbtn_back.setOnClickListener(this);
        recyclerViewAdapter.setOnClickTypeListener(this);
        chat_title_remove.setOnClickListener(this);
        adapter.setOnMessageLongClickListener(this);
        chat_input.setOnLongClickListener(this);

        voiceButton.setAudioFinishRecorderListener(new AudioRecordButton.AudioFinishRecorderListener() {
            @Override
            public void onFinished(int seconds, String filePath) {
                Recorder recorder = new Recorder(seconds, filePath);
                EMConversation conversation = EMChatManager.getInstance().getConversation(contentName);
                EMMessage emMessage = conversation.getLastMessage();

//                mDatas.add(recorder);
                recorder.setFilePathString(filePath);
                recorder.setTime(seconds);

                chat_message.setSelection(mDatas.size() - 1);
                GoHomeHelper.getInstance().sendVoiceMessage(filePath, seconds);
                handler.sendEmptyMessage(200);


            }
        });
        chat_message.setOnItemClickListener(new AdapterView.OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> parent, View view,
                                    int position, long id) {
                // TODO Auto-generated method stub
                // 播放动画
                if (viewanim != null) {//让第二个播放的时候第一个停止播放
                    viewanim.setBackgroundResource(R.mipmap.ic_launcher);
                    viewanim = null;
                }
                viewanim = view.findViewById(R.id.id_recorder_anim);
                viewanim.setBackgroundResource(R.drawable.play);
                AnimationDrawable drawable = (AnimationDrawable) viewanim
                        .getBackground();
                drawable.start();

                // 播放音频
                MediaManager.playSound(mDatas.get(position).getFilePathString(),
                        new MediaPlayer.OnCompletionListener() {

                            @Override
                            public void onCompletion(MediaPlayer mp) {
                                viewanim.setBackgroundResource(R.mipmap.ic_launcher);

                            }
                        });
            }
        });
    }

    private BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {

            handler.sendEmptyMessage(200);
        }
    };

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.keyboard:
                keyboard.setVisibility(View.GONE);
                linearLayout.setVisibility(View.VISIBLE);
                break;
            case R.id.chat_voice:
                keyboard.setVisibility(View.VISIBLE);
                frameLayout.setVisibility(View.VISIBLE);
                linearLayout.setVisibility(View.GONE);
                break;
            case R.id.chat_send: // 发送
                handler.sendEmptyMessage(200);
                GoHomeHelper.getInstance().sendTXTMessage(contentName, chat_input.getText().toString().trim()
                        , chattype);
                chat_input.setText("");
                break;
            case R.id.chat_type: // 加号
                GoHomeHelper.getInstance().hideKeyboard(chat_input);
                chat_facechoose.setVisibility(View.GONE);
                chat_recyclerView.setVisibility(View.VISIBLE);
                break;
            case R.id.chat_input: // 输入框
                GoHomeHelper.getInstance().showKeyboard(chat_input);
                chat_facechoose.setVisibility(View.GONE);
                chat_recyclerView.setVisibility(View.GONE);
                break;
            case R.id.chat_face: // 表情
                GoHomeHelper.getInstance().hideKeyboard(chat_input);
                chat_facechoose.setVisibility(View.VISIBLE);
                chat_recyclerView.setVisibility(View.GONE);
                break;
            case R.id.chat_imgbtn_back: // 返回键
                finish();
                break;
            case R.id.chat_title_remove: //删除聊天记录
                showDialog("确定清除所有聊天记录么", true, "");
                break;
        }
    }

    private int clickPosition; // 点击的位置


    /**
     * 友好提示Dialog flag值为true是删除所有消息 为false是删除一条消息
     */
    public void showDialog(String message, final boolean flag, final String msgId) {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("提示");
        builder.setMessage(message);
        builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                if (flag) {
                    GoHomeHelper.getInstance().deleteConversation(contentName);
                } else {
                    GoHomeHelper.getInstance().deleteMessage(contentName, msgId);
                    ToastUtil.showToast("该条消息已删除");
                }
                handler.sendEmptyMessage(200);
            }
        });
        builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
            }
        });
        builder.show();
    }

    private SharedPreferences sharedPreferences;
    private SharedPreferences.Editor editor;
    private boolean isInitSharedPreferences = false;

    public synchronized void initSharedPreferences() {
        if (!isInitSharedPreferences) {
            sharedPreferences = getSharedPreferences("chat_copy_message", MODE_PRIVATE);
            editor = sharedPreferences.edit();
            isInitSharedPreferences = true;
        }

    }

    /************************************************ 表情********************************************************************/

    /**
     * 表情页的监听事件
     */
    private OnCorpusSelectedListener mListener;

    /**
     * 显示表情页的viewpager
     */
    private ViewPager vp_face;

    /**
     * 表情页界面集合
     */
    private ArrayList<View> pageViews;

    /**
     * 游标显示布局
     */
    private LinearLayout layout_point;

    /**
     * 游标点集合
     */
    private ArrayList<ImageView> pointViews;

    /**
     * 表情集合
     */
    private List<List<ChatEmoji>> emojis;

    /**
     * 表情区域
     */
    private View faceView;

    /**
     * 表情数据填充器
     */
    private List<FaceAdapter> faceAdapters;

    /**
     * 当前表情页
     */
    private int current = 0;


    public void setOnCorpusSelectedListener(OnCorpusSelectedListener listener) {
        mListener = listener;
    }

    private final String IMAGE_TYPE = "image/*";
    private final int IMAGE_CODE = 0;

    /**
     * 相机,图片,位置,视频等点击事件
     */
    @Override
    public void onClikType(int position) {
        switch (position) {
            case 0: // 拍照
                Intent cameraIntent = new Intent(Intent.ACTION_PICK);
                cameraIntent.setAction(MediaStore.ACTION_IMAGE_CAPTURE);
                imageFileUri = getOutFileUri(TYPE_FILE_IMAGE);
                cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, imageFileUri);
                startActivityForResult(cameraIntent, SYSTEM_CAMERA_REQUESTCODE);
                break;
            case 1: // 图片
                Intent intent = new Intent(Intent.ACTION_PICK);
                intent.setType(IMAGE_TYPE);
                startActivityForResult(intent, IMAGE_CODE);
                break;
            case 2: // 位置
                Intent locationIntent = new Intent(ChatActivity.this,
                        LocationActivity.class);
                startActivityForResult(locationIntent,400);
                break;
            case 3: // 视频
                break;
            case 4: // 文件
//                selectFileFromLocal();
                Intent intent2 = new Intent(Intent.ACTION_PICK);
                intent2.setType(IMAGE_TYPE);
                startActivityForResult(intent2, IMAGE_CODE);
                break;
            case 5: // 语音通话
                break;
            case 6: // 视频通话
                break;
        }
    }


    /**
     * 选择文件
     */
    private void selectFileFromLocal() {
        Intent intent = null;
        if (Build.VERSION.SDK_INT < 19){//19以后这个api不可用
            intent = new Intent(Intent.ACTION_GET_CONTENT);
            intent.setType("*/*");
            intent.addCategory(Intent.CATEGORY_OPENABLE);
        }else {
            intent = new Intent(
                    Intent.ACTION_PICK,
                    android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);

        }
        startActivityForResult(intent,REQUEST_CODE_SELECT_FILE);
    }

    private void getSysImages() {
        Intent imgPathIntent = new Intent(Intent.ACTION_GET_CONTENT);
        imgPathIntent.setType(IMAGE_TYPE);
        startActivityForResult(imgPathIntent, REQUEST_CODE_PICK_IMAGE);
    }

    //重写onActivityResult以获得你需要的信息

    @Override

    protected void onActivityResult(int requestCode, int resultCode, Intent data) {


        //调出系统照相机照相,并显示图片
        if (requestCode == SYSTEM_CAMERA_REQUESTCODE && resultCode == RESULT_OK) {
            /*从保存的文件中取这个拍好的图片*/
            Log.i("MyPicture", imageFileUri.getEncodedPath());
//            setPicToImageView((ImageView) findViewById(R.id.chat_item_me_img)
//                    , new File(imageFileUri.getEncodedPath()));

        }

        if (resultCode != RESULT_OK) {        //此处的 RESULT_OK 是系统自定义得一个常量

            Log.e("wcl", "ActivityResult resultCode error");

            return;

        }

        Bitmap bm = null;

        //外界的程序访问ContentProvider所提供数据 可以通过ContentResolver接口

        ContentResolver resolver = getContentResolver();

        //此处的用于判断接收的Activity是不是你想要的那个

        if (requestCode == IMAGE_CODE) {

            try {

                Uri originalUri = data.getData();        //获得图片的uri

                bm = MediaStore.Images.Media.getBitmap(resolver, originalUri);        //显得到bitmap图片

                String[] proj = {MediaStore.Images.Media.DATA};

                //好像是android多媒体数据库的封装接口，具体的看Android文档

                Cursor cursor = managedQuery(originalUri, proj, null, null, null);

                //按我个人理解 这个是获得用户选择的图片的索引值

                int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);

                //将光标移至开头 ，这个很重要，不小心很容易引起越界

                cursor.moveToFirst();

                //最后根据索引值获取图片路径

                String path = cursor.getString(column_index);
                GoHomeHelper.getInstance().sendImageMessage(contentName, path, chattype);
                Log.i("wcl", path + " 图片路径");

            } catch (IOException e) {

                Log.e("wcl", e.toString());

            }

        }else if (requestCode == REQUEST_CODE_SELECT_FILE){// 发送文件
            if (data != null){
                Uri uri = data.getData();
                if (uri != null){
                    sendFile(uri);
                }
            }

            if (requestCode == 400){
                String address = data.getStringExtra("address");
                double latitude = data.getDoubleExtra("latitude", 0);
                double longitude = data.getDoubleExtra("longitude",0);
                GoHomeHelper.getInstance().sendLocationMessage(contentName,address,latitude,longitude,chattype);

            }
        }

    }

    /**
     * 发送文件
     * @param uri
     */
    private void sendFile(Uri uri) {
        String filePath = null;
        if ("content".equalsIgnoreCase(uri.getScheme())){
            String[] projection = {"_data"};
            Cursor cursor = null;
            try{

            cursor = getContentResolver().query(uri,projection,null,null,null);
            int column_index = cursor.getColumnIndexOrThrow("_data");
            if (cursor.moveToFirst()){
                filePath = cursor.getString(column_index);
            }
            }catch (Exception e){
                e.printStackTrace();
            }
        }else if ("file".equalsIgnoreCase(uri.getScheme())){
            filePath = uri.getPath();
        }
        File file = new File(filePath);
        if (file == null || !file.exists()) {
            Toast.makeText(this, "文件不存在", Toast.LENGTH_SHORT).show();
            return;
        }
        if (file.length() > 10 * 1024 * 1024) {
            Toast.makeText(this, "文件不能大于10M", Toast.LENGTH_SHORT).show();
            return;
        }
        //创建一个文件消息
//        EMMessage message = EMMessage.createSendMessage(EMMessage.Type.FILE);
//        //如果是群聊,设置chattype,默认是单聊
//        if (chatType == CHATTYPE_GROUP)
//            message.setChatType(EMMessage.ChatType.GroupChat);
//
////        message.setReceipt(toChatUsername);
//        //add message body
//        NormalFileMessageBody body = new NormalFileMessageBody(new File(filePath));
//        message.addBody(body);
//        message.setAttribute("toUserNick", toUserNick);
//        message.setAttribute("usernick", myUserNick);
//        conversation.addMessage(message);
//        chat_message.setAdapter(adapter);
//        adapter.refresh();
//        chat_message.setSelection(chat_message.getCount() -1);
//        setResult(RESULT_OK);

    }



    @Override
    public void onMessageLongClick(View view, String msgId, String message) {
        popupMenu(view, msgId, message);
    }

    @Override
    public boolean onLongClick(View v) {
        switch (v.getId()) {
            case R.id.chat_input:
                popupMenuPaste(v);
                break;
        }
        return false;
    }


    public interface OnCorpusSelectedListener {

        void onCorpusSelected(ChatEmoji emoji);

        void onCorpusDeleted();
    }

    private void initEmojis() {
        Init_View();
        Init_viewPager();
        Init_Point();
        Init_Data();
    }

    /**
     * 初始化控件
     */
    private void Init_View() {
        vp_face = (ViewPager) findViewById(R.id.chat_contains);
        layout_point = (LinearLayout) findViewById(R.id.iv_image);
        // chattext.setOnClickListener(this);
    }

    private void Init_viewPager() {
        pageViews = new ArrayList<View>();
        // 左侧添加空页
        View nullView1 = new View(this);
        // 设置透明背景
        nullView1.setBackgroundColor(0x00000000);
        pageViews.add(nullView1);

        // 中间添加表情页

        faceAdapters = new ArrayList<FaceAdapter>();
        for (int i = 0; i < emojis.size(); i++) {
            GridView view = new GridView(this);
            FaceAdapter adapter = new FaceAdapter(this, emojis.get(i));
            view.setAdapter(adapter);
            faceAdapters.add(adapter);
            view.setOnItemClickListener(this);
            view.setNumColumns(7);
            view.setBackgroundColor(0x00000000);
            view.setHorizontalSpacing(1);
            view.setVerticalSpacing(1);
            view.setStretchMode(GridView.STRETCH_COLUMN_WIDTH);
            view.setCacheColorHint(0);
            view.setPadding(5, 0, 5, 0);
            view.setSelector(new ColorDrawable(0x00000000));
            view.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.FILL_PARENT,
                    LinearLayout.LayoutParams.WRAP_CONTENT));
            view.setGravity(Gravity.CENTER);
            pageViews.add(view);
        }

        // 右侧添加空页面
        View nullView2 = new View(this);
        // 设置透明背景
        nullView2.setBackgroundColor(0x00000000);
        pageViews.add(nullView2);
    }

    /**
     * 初始化游标
     */
    private void Init_Point() {

        pointViews = new ArrayList<ImageView>();
        ImageView imageView;
        for (int i = 0; i < pageViews.size(); i++) {
            imageView = new ImageView(this);
            imageView.setBackgroundResource(R.mipmap.d1);
            LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(
                    new ViewGroup.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT,
                            LinearLayout.LayoutParams.WRAP_CONTENT));
            layoutParams.leftMargin = 10;
            layoutParams.rightMargin = 10;
            layoutParams.width = 8;
            layoutParams.height = 8;
            layout_point.addView(imageView, layoutParams);
            if (i == 0 || i == pageViews.size() - 1) {
                imageView.setVisibility(View.GONE);
            }
            if (i == 1) {
                imageView.setBackgroundResource(R.mipmap.d2);
            }
            pointViews.add(imageView);

        }
    }

    /**
     * 填充数据
     */
    private void Init_Data() {
        vp_face.setAdapter(new ViewPagerAdapter(pageViews));

        vp_face.setCurrentItem(1);
        current = 0;
        vp_face.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {

            @Override
            public void onPageSelected(int arg0) {
                current = arg0 - 1;
                // 描绘分页点
                draw_Point(arg0);
                // 如果是第一屏或者是最后一屏禁止滑动，其实这里实现的是如果滑动的是第一屏则跳转至第二屏，如果是最后一屏则跳转到倒数第二屏.
                if (arg0 == pointViews.size() - 1 || arg0 == 0) {
                    if (arg0 == 0) {
                        vp_face.setCurrentItem(arg0 + 1);// 第二屏 会再次实现该回调方法实现跳转.
                        pointViews.get(1).setBackgroundResource(R.mipmap.d2);
                    } else {
                        vp_face.setCurrentItem(arg0 - 1);// 倒数第二屏
                        pointViews.get(arg0 - 1).setBackgroundResource(
                                R.mipmap.d2);
                    }
                }
            }

            @Override
            public void onPageScrolled(int arg0, float arg1, int arg2) {

            }

            @Override
            public void onPageScrollStateChanged(int arg0) {

            }
        });

    }

    /**
     * 绘制游标背景
     */
    public void draw_Point(int index) {
        for (int i = 1; i < pointViews.size(); i++) {
            if (index == i) {
                pointViews.get(i).setBackgroundResource(R.mipmap.d2);
            } else {
                pointViews.get(i).setBackgroundResource(R.mipmap.d1);
            }
        }
    }

    @Override
    public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
        ChatEmoji emoji = (ChatEmoji) faceAdapters.get(current).getItem(arg2);
        if (emoji.getId() == R.drawable.face_del_icon) {
            int selection = chat_input.getSelectionStart();
            String text = chat_input.getText().toString();
            if (selection > 0) {
                String text2 = text.substring(selection - 1);
                if ("]".equals(text2)) {
                    int start = text.lastIndexOf("[");
                    int end = selection;
                    chat_input.getText().delete(start, end);
                    return;
                }
                chat_input.getText().delete(selection - 1, selection);
            }
        }
        if (!TextUtils.isEmpty(emoji.getCharacter())) {
            if (mListener != null)
                mListener.onCorpusSelected(emoji);
            SpannableString spannableString = FaceConversionUtil.getInstace()
                    .addFace(this, emoji.getId(), emoji.getCharacter());
            chat_input.append(spannableString);
        }

    }

//    @Override
//    public boolean onCreateOptionsMenu(Menu menu) {
//        getMenuInflater().inflate(R.menu.menu_chat,menu);
//        return true;
//    }

    /*********************************************************************************************/


    /**
     * popupMenu初始化
     */
    public void popupMenu(View view, final String msgId, final String message) {
        PopupMenu popupMenu = new PopupMenu(this, view);
        MenuInflater inflater = popupMenu.getMenuInflater();
        popupMenu.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
            @Override
            public boolean onMenuItemClick(MenuItem item) {
                switch (item.getItemId()) {
                    case R.id.menu_chat_copy:
                        initSharedPreferences();
                        editor.putString("chat_message", message);
                        editor.commit();
                        ToastUtil.showToast("复制");
                        return true;
                    case R.id.menu_chat_paste:
                        //  GoHomeHelper.getInstance().deleteMessage(contentName, datas.get(clickPosition).getBody().toString());
                        ToastUtil.showToast("粘贴");
                        return true;
                    case R.id.menu_chat_deleteMessage:
                        showDialog("确定删除该条消息", false, msgId);

                        return true;
                    default:
                        return false;
                }
            }
        });
        inflater.inflate(R.menu.menu_chat, popupMenu.getMenu());
        popupMenu.show();
    }

    /**
     * 初始化粘贴popupmenu
     */
    public void popupMenuPaste(View view) {
        PopupMenu popupMenu = new PopupMenu(this, view);
        MenuInflater inflater = popupMenu.getMenuInflater();
        popupMenu.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
            @Override
            public boolean onMenuItemClick(MenuItem item) {
                switch (item.getItemId()) {
                    case R.id.menu_chat_paste:
                        initSharedPreferences();
                        String text = TextUtil.splitTxt(sharedPreferences.getString("chat_message", ""));
                        SpannableString spannableString = FaceConversionUtil.getInstace().
                                getExpressionString(ChatActivity.this, chat_input.getText().toString() + text);
                        chat_input.setText(spannableString);

                        ToastUtil.showToast("粘贴");
                        return true;
                    default:
                        return false;
                }
            }
        });
        inflater.inflate(R.menu.menu_paste, popupMenu.getMenu());
        popupMenu.show();
    }

    @Override
    protected void onDestroy() {
        GoHomeHelper.getInstance().readMessage(contentName);
        super.onDestroy();

        MediaManager.release();
    }


    //-----------------------Android大图的处理方式---------------------------
    private void setPicToImageView(ImageView imageView, File imageFile) {
        int imageViewWidth = imageView.getWidth();
        int imageViewHeight = imageView.getHeight();
        BitmapFactory.Options opts = new BitmapFactory.Options();

        //设置这个，只得到Bitmap的属性信息放入opts，而不把Bitmap加载到内存中
        opts.inJustDecodeBounds = true;
        BitmapFactory.decodeFile(imageFile.getPath(), opts);

        int bitmapWidth = opts.outWidth;
        int bitmapHeight = opts.outHeight;

        int scale = Math.max(imageViewWidth / bitmapWidth, imageViewHeight / bitmapHeight);

        //缩放的比例
        opts.inSampleSize = scale;
        //内存不足时可被回收
        opts.inPurgeable = true;
        //设置为false,表示不仅Bitmap的属性，也要加载bitmap
        opts.inJustDecodeBounds = false;

        Bitmap bitmap = BitmapFactory.decodeFile(imageFile.getPath(), opts);
        imageView.setImageBitmap(bitmap);
    }

    //-----------------------生成Uri---------------------------------------
    //得到输出文件的URI
    private Uri getOutFileUri(int fileType) {
        return Uri.fromFile(getOutFile(fileType));
    }

    //生成输出文件
    private File getOutFile(int fileType) {

        String storageState = Environment.getExternalStorageState();
        if (Environment.MEDIA_REMOVED.equals(storageState)) {
            Toast.makeText(getApplicationContext(), "oh,no, SD卡不存在", Toast.LENGTH_SHORT).show();
            return null;
        }

        File mediaStorageDir = new File(Environment
                .getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES)
                , "MyPictures");
        if (!mediaStorageDir.exists()) {
            if (!mediaStorageDir.mkdirs()) {
                Log.i("MyPictures", "创建图片存储路径目录失败");
                Log.i("MyPictures", "mediaStorageDir : " + mediaStorageDir.getPath());
                return null;
            }
        }

        File file = new File(getFilePath(mediaStorageDir, fileType));

        return file;
    }

    //生成输出文件路径
    private String getFilePath(File mediaStorageDir, int fileType) {
        String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss")
                .format(new Date());
        String filePath = mediaStorageDir.getPath() + File.separator;
        if (fileType == TYPE_FILE_IMAGE) {
            filePath += ("IMG_" + timeStamp + ".jpg");
        } else if (fileType == TYPE_FILE_VEDIO) {
            filePath += ("VIDEO_" + timeStamp + ".mp4");
        } else {
            return null;
        }
        return filePath;
    }

    @Override
    protected void onPause() {
        // TODO Auto-generated method stub
        super.onPause();
        MediaManager.pause();
    }

    protected EaseChatFragmentListener chatFragmentListener;
    public void setChatFragmentListener(EaseChatFragmentListener chatFragmentListener){
        this.chatFragmentListener = chatFragmentListener;
    }

    public interface EaseChatFragmentListener{
        /**
         * 设置消息扩展属性
         */
        void onSetMessageAttributes(EMMessage message);

        /**
         * 进入会话详情
         */
        void onEnterToChatDetails();

        /**
         * 用户头像点击事件
         * @param username
         */
        void onAvatarClick(String username);

        /**
         * 消息气泡框点击事件
         */
        boolean onMessageBubbleClick(EMMessage message);

        /**
         * 消息气泡框长按事件
         */
        void onMessageBubbleLongClick(EMMessage message);

        /**
         * 扩展输入栏item点击事件,如果要覆盖EaseChatFragment已有的点击事件，return true
         * @param view
         * @param itemId
         * @return
         */
        boolean onExtendMenuItemClick(int itemId, View view);

        /**
         * 设置自定义chatrow提供者
         * @return
         */
//        EaseCustomChatRowProvider onSetCustomChatRowProvider();
//    @Override
//    protected void onResume() {
//        // TODO Auto-generated method stub
//        super.onResume();
//        MediaManager.resume();
//    }
    }
}
